package org.example.k8s_cloudplatform.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.kubernetes.client.openapi.ApiException;
import jakarta.annotation.Resource;
import org.example.k8s_cloudplatform.K8S_mapper.NamespaceMapper;
import org.example.k8s_cloudplatform.entity.Pod;
import org.example.k8s_cloudplatform.entity.PodRequest;
import org.example.k8s_cloudplatform.entity.User;
import org.example.k8s_cloudplatform.entity.res.PasswordChanger;
import org.example.k8s_cloudplatform.entity.res.Result;
import org.example.k8s_cloudplatform.mapper.PodMapper;
import org.example.k8s_cloudplatform.mapper.PodRequestMapper;
import org.example.k8s_cloudplatform.mapper.UserMapper;
import org.example.k8s_cloudplatform.scheduler.ExpirationScheduler;
import org.example.k8s_cloudplatform.service.Impl.UserServiceImpl;
import org.example.k8s_cloudplatform.utils.CheckUtil;
import org.example.k8s_cloudplatform.utils.EmailVerifyUtil;
import org.example.k8s_cloudplatform.utils.JwtUtil;
import org.example.k8s_cloudplatform.utils.MD5Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service
public class UserService extends ServiceImpl<UserMapper, User> implements UserServiceImpl {
    @Resource
    private UserMapper userMapper;
    @Resource
    private NamespaceMapper namespaceMapper;
    @Resource
    private PodMapper podMapper;

    @Resource
    private PodRequestMapper podRequestMapper;
    //糟糕的用法，但是暂时先这样
    @Resource
    private PodService podService;
    private final Logger logger = LoggerFactory.getLogger(ExpirationScheduler.class);

    public boolean checkPassword(Integer userID, String password) {
        User user = userMapper.selectById(userID);
        if (user == null) return false;
        else return MD5Util.verify(password, user.getPassword());
    }
    public Result login(User user) {
        User checker = userMapper.selectById(user.getID());
        if (checker == null) return Result.fail("用户不存在", null);
        else {
            try {
                if (!MD5Util.verify(user.getPassword(), checker.getPassword()))
                    return Result.fail("用户名或密码错误", null);
                else{//成功登录
                    try {
                        //返回鉴权token
                        Map<String, Object> res = new HashMap<>();
                        res.put("token", JwtUtil.createJwt(checker.getID(), checker.getJob()));
                        res.put("job",checker.getJob());
                        return Result.success(res);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return Result.exception();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return Result.exception();
            }
        }
    }
    @Transactional
    public Result register(User user) {
        user.setStatus(0);//激活
        user.setJob(0);//仅开放普通用户
        if (Objects.equals(user.getName(), ""))
            return Result.fail("名字必须存在",null);
        if (Objects.equals(user.getPassword(), ""))
            return Result.fail("密码必须存在",null);
        if (user.getPassword().length() < 8)
            return Result.fail("密码不得小于8位",null);
        //密码加密
        user.setPassword(MD5Util.md5(user.getPassword()));
        userMapper.insert(user);

        //在K8s中注册，创建命名空间
        //创建ns并将新的ns赋值给namespace
        try {
            namespaceMapper.create(userMapper.getMaxId()+"");
        } catch (ApiException e) {
            e.printStackTrace();
            System.out.println(e.getResponseBody());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.exception();
        }
        return Result.success();
    }

    public Result updateInfo(User user){
        String password=userMapper.selectById(user.getID()).getPassword();
        user.setPassword(password);
        if(user.getTelephone()!=null&&!CheckUtil.isMobile(user.getTelephone())){
            return Result.fail("手机号格式错误",null);
        }else if(user.getEmail()!=null&&!CheckUtil.isEmail(user.getEmail())){
            return Result.fail("邮箱格式错误",null);
        }else {
            userMapper.updateById(user);
            return Result.success();
        }
    }
    public Result updatePassword(PasswordChanger passwordChanger){
        if(passwordChanger.getNewPassword().length()<8){
            return Result.fail("新密码不得小于8位",null);
        }
        User user=userMapper.selectById(passwordChanger.getID());
        if(!MD5Util.verify(passwordChanger.getOriginalPassword(),user.getPassword())){
            return Result.fail("旧密码错误",null);
        }
        user.setPassword(MD5Util.md5(passwordChanger.getNewPassword()));
        userMapper.updateById(user);
        return Result.success();
    }

    public Result delete(User user){
        if(user.getStatus()!=0)
            return Result.fail( "用户状态异常",null);
        if (user.getJob() == 1)
            return Result.fail("管理员不能直接被注销",null);
        user.setStatus(1);//注销
        if(user.getEmail()!=null&&CheckUtil.isEmail(user.getEmail())){
            //发送邮件
            try {
                EmailVerifyUtil.sendMail(user.getEmail(),"山东大学Docker云平台通知",
                        "您的账号(ID:"+user.getID()+")已被注销。" +
                                "<br>如有疑问请联系平台管理员");
            } catch (Exception e) {
                e.printStackTrace();
                logger.error("账号(ID:"+user.getID()+")邮件发送失败");
                return Result.exception();
            }
        }
        userMapper.updateById(user);
        //需要处理所有该用户的podRequest
        LambdaQueryWrapper<PodRequest> podRequestWrapper= Wrappers.lambdaQuery();
        podRequestWrapper.eq(PodRequest::getUserID,user.getID());
        podRequestWrapper.eq(PodRequest::getStatus,0);//仅消除未处理的podRequest
        podRequestMapper.delete(podRequestWrapper);
        //需要依次回收该用户的所有资源（ns，svc，pod）
        LambdaQueryWrapper<Pod> podWrapper= Wrappers.lambdaQuery();
        podWrapper.eq(Pod::getStatus,0);//仅看到已激活的pod
        podWrapper.eq(Pod::getUserID,user.getID());
        List<Pod> podList = podMapper.selectList(podWrapper);
        for (Pod pod : podList) {
            podService.delete(pod.getId(),0);
        }
        try {
            namespaceMapper.delete(user.getID()+"");
        } catch (ApiException e) {
            e.printStackTrace();
            System.out.println(e.getResponseBody());
            return Result.exception("在注销用户NameSpace时出错,请考虑手动处理");
        }
        return Result.success();
    }

    public Result passwordReset(User user) {
        user.setPassword(MD5Util.md5("12345678"));
        userMapper.updateById(user);
        if (user.getEmail()!=null&&CheckUtil.isEmail(user.getEmail())){
            //发送邮件
            try {
                EmailVerifyUtil.sendMail(user.getEmail(),"山东大学Docker云平台通知",
                        "您的账号(ID:"+user.getID()+")密码已重置为12345678，请及时修改密码。如有疑问请联系平台管理员");
            } catch (Exception e) {
                e.printStackTrace();
                return Result.exception();
            }
        }
        return Result.success();
    }
}